package net.pws.common.beanutils.converter;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author dz
 */
public class DateConverter extends AbstractConverter {
    
    private SimpleDateFormat[] formats;
    
    public DateConverter() {
        formats = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd") };
    }
    
    public DateConverter(String formatPattern) {
        if (StringUtils.isEmpty(formatPattern)) {
            throw new IllegalArgumentException();
        }
        formats = new SimpleDateFormat[] { new SimpleDateFormat(formatPattern) };
    }
    
    public DateConverter(String[] formatPatterns) {
        if (0 == formatPatterns.length) {
            throw new IllegalArgumentException();
        }
        formats = new SimpleDateFormat[formatPatterns.length];
        for (int i = 0; i < formatPatterns.length; i++) {
            formats[i] = new SimpleDateFormat(formatPatterns[i]);
        }
    }
    
    @SuppressWarnings("rawtypes")
	public Object convert(Class clazz, Object value) {
        for (int i = 0; i < formats.length; i++) {
            try {
                if (value instanceof Date) {
                    return value;
                }
                if (value instanceof String) {
                    String dateStr = (String) value;
                    if (StringUtils.isNotBlank(dateStr) && formats[i].toPattern()
                                                                     .length() == dateStr.length()) {
                        return formats[i].parse(dateStr);
                    }
                }
            }
            catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        return null;
    }
    
}
